package com.components.base.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.text.TextUtils
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class CustomMarqueeView : AppCompatTextView {

    //View宽度
    private var mViewWidth = 0
    private var mViewHeight = 0
    private var mScrollX = 0F
    private var mMarqueeMode = 3
    private val rect = Rect()

    constructor(context: Context) : this(context, null){

    }
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0){

    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        includeFontPadding = false
        setAttr()
    }

    override fun onDraw(canvas: Canvas?) {
        val textContentText = text.toString().trim()
        if (TextUtils.isEmpty(textContentText)) {
            return
        }
        val x = mViewWidth - mScrollX
        val y = mViewHeight / 2F + getTextContentHeight() / 2
        canvas?.drawText(textContentText, x, y, paint)
        mScrollX += mMarqueeMode
        if (mScrollX >= (mViewWidth + getTextContentWidth())) {
            mScrollX = 0F
        }
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mViewWidth = MeasureSpec.getSize(widthMeasureSpec)
        mViewHeight = MeasureSpec.getSize(heightMeasureSpec)
    }

    /**
     * 测量文字宽度
     * @return 文字宽度
     */
    private fun getTextContentWidth(): Int {
        val textContent = text.toString().trim()
        if (!TextUtils.isEmpty(textContent)) {
            paint.getTextBounds(textContent, 0, textContent.length, rect)
            return rect.width()
        }
        return 0
    }

    /**
     * 测量文字高度
     * @return 文字高度
     */
    private fun getTextContentHeight(): Int {
        val textContent = text.toString().trim()
        if (!TextUtils.isEmpty(textContent)) {
            paint.getTextBounds(textContent, 0, textContent.length, rect)
            return rect.height()
        }
        return 0
    }

    /**
     * 始终获取焦点
     * 跑马灯在TextView处于焦点状态的时候才会滚动
     */
    override fun isFocused(): Boolean {
        return true
    }

    /**
     * 设置相关属性
     */
    private fun setAttr() {
        this.ellipsize = TextUtils.TruncateAt.MARQUEE //设置跑马灯效果
        this.marqueeRepeatLimit = 1 //设置跑马灯重复次数
        this.isSingleLine = true //设置单行
    }
}